package org.hgvc.webapp.ets.jsf.beans.mastersetup;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.faces.component.UIParameter;
import javax.faces.event.ActionEvent;

import org.hgvc.webapp.ets.bo.Branch;
import org.hgvc.webapp.ets.constant.CommonConstant;
import org.hgvc.webapp.ets.spring.service.MasterSetupService;
import org.jocsb.base.AbstractBean;
import org.jocsb.base.exception.BaseException;


public class BranchBean extends AbstractBean {
	public static final String BEAN_NAME="branchBean";
	private MasterSetupService service;
	private List<Branch> branchList;
	private Branch branch;
	public static final String NAV_LIST_BRANCH="listBranch";
	public static final String NAV_ADD_BRANCH="addBranch";
	public static final String NAV_EDIT_BRANCH="editBranch";
	 
	public MasterSetupService getService() {
		return service;
	}
	public void setService(MasterSetupService service) {
		this.service = service;
	}
	public Branch getBranch() {
		return branch;
	}
	public void setBranch(Branch branch) {
		this.branch = branch;
	}
	public List<Branch> getBranchList() {
		try{
			branchList = service.getBranchList();
		}catch(BaseException ex){
			ex.printStackTrace();
			initErrorBean(ex);
		}
		return branchList;
	}
	public void setBranchList(List<Branch> branchList) {
		this.branchList = branchList;
	}
	
	public String navCreationAction(){
		branch = new Branch();
		return NAV_ADD_BRANCH;
	}
	
	public String createAction(){
		try{
			branch.setCreatedBy(getThisUser());
			branch.setCreatedDate(new Date());
			branch.setIsDeleted(CommonConstant.NOT_DELETED);
			service.saveBranch(branch);
			return NAV_LIST_BRANCH;
		}catch(BaseException ex){
			ex.printStackTrace();
			initErrorBean(ex);
		}
		return NAV_ADD_BRANCH;
	}
	
	public void editListener(ActionEvent actionEvent){
		branch = null;
		UIParameter parameter = (UIParameter)actionEvent.getComponent().findComponent("branchId");
		String branchId = (String)parameter.getValue();
		for(Branch b:branchList){
			if(b.getBranchId().equalsIgnoreCase(branchId)){
				branch = b;
				break;
			}
		}
	}
	
	public String navEditAction(){
		return NAV_EDIT_BRANCH;
	}
	
	public String editAction(){
		try{
			branch.setModifiedBy(getThisUser());
			branch.setModifiedDate(new Date());
			service.updateBranch(branch);
			return NAV_LIST_BRANCH;
		}catch(BaseException ex){
			ex.printStackTrace();
			initErrorBean(ex);
		}
		
		return NAV_EDIT_BRANCH;
	}
	
	public String deleteAction(){
		try{
			
			List<Branch> deleteList = new ArrayList<Branch>();
			for(Branch b:branchList){
				if(b.isMarkAsAction()){
					deleteList.add(b);
				}
			}
			service.deleteBranches(deleteList);
		}catch(BaseException ex){
			ex.printStackTrace();
			initErrorBean(ex);
		}
		return NAV_LIST_BRANCH;
	}
}
